<template>
    <div class="stock-manage-container layout-padding">
        <div class="stock-manage-padding layout-padding-view layout-padding-auto">
            <!-- 搜索区域 -->
            <div class="content-wrapper">
                <vxe-form v-bind="formOptions" v-on="formEvents"></vxe-form>
                <div style="margin-bottom: 10px;">
                    <el-button type="success" size="default" @click="handleAddProduct">添加商品</el-button>
                    <el-button type="primary" size="default" @click="handleInStock">入库</el-button>
                    <el-button type="warning" size="default" @click="handleOutStock">出库</el-button>
                    <!-- <el-button type="info" size="default" @click="handleStockCheck">库存盘点</el-button> -->
                </div>
                <!-- 表格区域 -->
                <div class="table-wrapper">
                    <vxe-table ref="tableRef" empty-text="没有更多数据了！" :loading="loading" round stripe border show-overflow
                        :data="tableData" :height="'100%'">
                        <vxe-column type="seq" width="60"></vxe-column>
                        <vxe-column field="productCode" title="商品编码"></vxe-column>
                        <vxe-column field="productName" title="商品名称"></vxe-column>
                        <vxe-column field="specification" title="规格"></vxe-column>
                        <vxe-column field="unit" title="单位"></vxe-column>
                        <vxe-column field="quantity" title="库存数量"></vxe-column>
                        <!-- <vxe-column field="warningQuantity" title="预警数量"></vxe-column>sa -->
                        <!-- <vxe-column field="status" title="状态">
                            <template #default="{ row }">
                                <el-tag :type="row.quantity <= row.warningQuantity ? 'danger' : 'success'">
                                    {{ row.quantity <= row.warningQuantity ? '库存不足' : '库存正常' }} </el-tag>
                            </template>
</vxe-column> -->
                        <vxe-column field="updatedAt" title="最后更新时间" width="180"></vxe-column>
                        <vxe-column title="操作" width="200" fixed="right">
                            <template #default="{ row }">
                                <el-button type="primary" size="small" @click="handleStockDetail(row)">库存明细</el-button>
                                <el-button type="warning" size="small" @click="handleStockEdit(row)">编辑</el-button>
                            </template>
                        </vxe-column>
                    </vxe-table>
                </div>
            </div>
            <div class="pagination-wrapper">
                <vxe-pager v-model:currentPage="pageVO.currentPage" v-model:pageSize="pageVO.pageSize"
                    :total="pageVO.total" @page-change="pageChange">
                </vxe-pager>
            </div>
        </div>
        <!-- 分页区域 -->


        <!-- 入库弹窗 -->
        <el-dialog title="入库操作" v-model="inStockDialogVisible" width="500px" :close-on-click-modal="false">
            <el-form :model="inStockForm" label-width="100px">
                <el-form-item label="商品" required>
                    <el-select v-model="inStockForm.productId" filterable placeholder="请选择商品">
                        <el-option v-for="item in stockListAll" :key="item.id" :label="item.productName"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="入库数量" required>
                    <el-input-number v-model="inStockForm.quantity" :min="1" :precision="0"></el-input-number>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="inStockForm.remark" type="textarea" :rows="3"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="inStockDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleInStockSubmit">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 出库弹窗 -->
        <el-dialog title="出库操作" v-model="outStockDialogVisible" width="500px" :close-on-click-modal="false">
            <el-form :model="outStockForm" label-width="100px">
                <el-form-item label="商品" required>
                    <el-select v-model="outStockForm.productId" filterable placeholder="请选择商品">
                        <el-option v-for="item in stockListAll" :key="item.id" :label="item.productName"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="出库数量" required>
                    <el-input-number v-model="outStockForm.quantity" :min="1" :precision="0"></el-input-number>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="outStockForm.remark" type="textarea" :rows="3"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="outStockDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleOutStockSubmit">确定</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 库存明细弹窗 -->
        <el-dialog title="库存明细" v-model="stockDetailDialogVisible" width="800px" :close-on-click-modal="false">
            <vxe-table :data="stockDetailData" height="400" stripe border>
                <vxe-column type="seq" width="60"></vxe-column>
                <vxe-column field="type" title="操作类型"></vxe-column>
                <vxe-column field="quantity" title="数量"></vxe-column>
                <vxe-column field="remark" title="备注"></vxe-column>
                <vxe-column field="createdAt" title="操作时间" width="180"></vxe-column>
            </vxe-table>
            <div class="pagination-wrapper" style="margin-top: 10px;">
                <vxe-pager
                    v-model:currentPage="stockDetailPageVO.currentPage"
                    v-model:pageSize="stockDetailPageVO.pageSize"
                    :total="stockDetailPageVO.total"
                    @page-change="stockDetailPageChange">
                </vxe-pager>
            </div>
        </el-dialog>

        <!-- 编辑库存弹窗 -->
        <el-dialog title="编辑库存" v-model="stockEditDialogVisible" width="500px" :close-on-click-modal="false">
            <el-form :model="stockEditForm" label-width="100px" :rules="stockEditRules" ref="stockEditFormRef">
                <el-form-item label="商品编码" prop="productCode">
                    <el-input v-model="stockEditForm.productCode"></el-input>
                </el-form-item>
                <el-form-item label="商品名称" prop="productName">
                    <el-input v-model="stockEditForm.productName"></el-input>
                </el-form-item>
                <el-form-item label="规格">
                    <el-input v-model="stockEditForm.specification"></el-input>
                </el-form-item>
                <el-form-item label="单位">
                    <el-input v-model="stockEditForm.unit"></el-input>
                </el-form-item>
                <el-form-item label="库存数量" required>
                    <el-input-number v-model="stockEditForm.quantity" :min="0" :precision="0"
                        disabled></el-input-number>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="stockEditForm.remark" type="textarea" :rows="3" placeholder="请输入备注"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="stockEditDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleStockEditSubmit">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 添加商品弹窗 -->
        <el-dialog title="添加商品" v-model="addProductDialogVisible" width="500px" :close-on-click-modal="false">
            <el-form :model="addProductForm" label-width="100px" :rules="addProductRules" ref="addProductFormRef">
                <el-form-item label="商品编码" prop="productCode">
                    <el-input v-model="addProductForm.productCode" placeholder="请输入商品编码"></el-input>
                </el-form-item>
                <el-form-item label="商品名称" prop="productName">
                    <el-input v-model="addProductForm.productName" placeholder="请输入商品名称"></el-input>
                </el-form-item>
                <el-form-item label="规格" prop="specification">
                    <el-input v-model="addProductForm.specification" placeholder="请输入规格"></el-input>
                </el-form-item>
                <el-form-item label="单位" prop="unit">
                    <el-input v-model="addProductForm.unit" placeholder="请输入单位"></el-input>
                </el-form-item>
                <el-form-item label="库存数量" prop="quantity">
                    <el-input-number v-model="addProductForm.quantity" :min="0" :precision="0"></el-input-number>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="addProductForm.remark" type="textarea" :rows="3" placeholder="请输入备注"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addProductDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleAddProductSubmit">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="stockManage">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { stockManageApi } from '/@/api/stockManage/index'

// 分页数据
const pageVO = reactive({
    total: 0,
    currentPage: 1,
    pageSize: 10
});

const searchData = ref({ productCode: '', productName: '' });
// 表单配置
const formOptions = reactive({
    data: {
        productCode: '',
        productName: '',
    },
    items: [
        { field: 'productCode', title: '商品编码', itemRender: { name: '$input', props: { placeholder: '请输入商品编码' } } },
        { field: 'productName', title: '商品名称', itemRender: { name: '$input', props: { placeholder: '请输入商品名称' } } },
        // {
        //     field: 'status', title: '状态', itemRender: {
        //         name: '$select', options: [
        //             { label: '全部', value: '' },
        //             { label: '库存不足', value: 'low' },
        //             { label: '库存正常', value: 'normal' }
        //         ]
        //     }
        // },
        {
            itemRender: {
                name: '$buttons', children: [
                    { props: { type: 'submit', content: '查询', status: 'primary' } },
                    { props: { type: 'reset', content: '重置' } }
                ]
            }
        }
    ]
});

// 表单事件
const formEvents = {
    submit: ({ data }) => {
        console.log('查询参数:', data);
        searchData.value = data;
        // 这里调用查询接口
        getStockList();
    }
};
let curStockDetailData = ref({}); // 当前商品数据
// 分页变化
const pageChange = ({ pageSize, currentPage }: { pageSize: number; currentPage: number }) => {
    pageVO.currentPage = currentPage;
    pageVO.pageSize = pageSize;
    getStockList()
};

// 表格数据
const loading = ref(false);
const tableData = ref([]);
const stockListAll = ref([]); // 商品数据

// 获取库存列表
const getStockList = () => {
    loading.value = true;
    let obj = {
        page: pageVO.currentPage,
        pageSize: pageVO.pageSize,
        productCode: searchData.value.productCode,
        productName: searchData.value.productName,
    }

    stockManageApi().getInventory(obj).then(res => {
        tableData.value = res.data.list
        pageVO.total = res.data.total
        loading.value = false;
    })
    // 这里调用获取库存列表的API
    // setTimeout(() => {
    //     tableData.value = [
    //         {
    //             productCode: 'P001',
    //             productName: '商品1',
    //             specification: '规格1',
    //             unit: '个',
    //             quantity: 100,
    //             warningQuantity: 50,
    //             lastUpdateTime: '2024-01-01 12:00:00'
    //         }
    //     ];


    // }, 500);
};

const getStockListAll = () => {
    let obj = {
        page: 1,
        pageSize: 9999,
    }

    stockManageApi().getInventory(obj).then(res => {
        stockListAll.value = res.data.list
    })
};
getStockListAll()

// 商品列表
const productList = ref([]);

// 获取商品列表
const getProductList = () => {
    // 这里调用获取商品列表的API
    setTimeout(() => {
        productList.value = [
            { id: 1, name: '商品1' },
            { id: 2, name: '商品2' }
        ];
    }, 500);
};

// 入库相关
const inStockDialogVisible = ref(false);
const inStockForm = reactive({
    productId: '',
    quantity: 1,
    remark: ''
});

const handleInStock = () => {
    inStockForm.productId = '';
    inStockForm.quantity = 1;
    inStockForm.remark = '';
    inStockDialogVisible.value = true;
};

const handleInStockSubmit = () => {
    if (!inStockForm.productId) {
        ElMessage.warning('请选择商品');
        return;
    }
    if (!inStockForm.quantity) {
        ElMessage.warning('请输入入库数量');
        return;
    }
    let obj = Object.assign({type:'入库',inventoryId:inStockForm.productId}, inStockForm)
    stockManageApi().transactionInventor(obj).then(res => {
        // 这里调用入库API
        ElMessage.success('入库成功');
        inStockDialogVisible.value = false;
        getStockList();
    })

};

// 出库相关
const outStockDialogVisible = ref(false);
const outStockForm = reactive({
    productId: '',
    quantity: 1,
    remark: ''
});

const handleOutStock = () => {
    outStockForm.productId = '';
    outStockForm.quantity = 1;
    outStockForm.remark = '';
    outStockDialogVisible.value = true;
};

const handleOutStockSubmit = () => {
    if (!outStockForm.productId) {
        ElMessage.warning('请选择商品');
        return;
    }
    if (!outStockForm.quantity) {
        ElMessage.warning('请输入出库数量');
        return;
    }

    let obj = Object.assign({type:'出库',inventoryId:outStockForm.productId}, outStockForm)
    stockManageApi().transactionInventor(obj).then(res => {
        // 这里调用入库API
        ElMessage.success('出库成功');
        outStockDialogVisible.value = false;
        getStockList();
    })
};

// 库存盘点
const handleStockCheck = () => {
    // 这里实现库存盘点逻辑
};

// 库存明细弹窗
const stockDetailDialogVisible = ref(false);
const stockDetailData = ref([]);
const stockDetailPageVO = reactive({
    total: 0,
    currentPage: 1,
    pageSize: 10
});

// 查看库存明细
const handleStockDetail = (row) => {
    curStockDetailData.value = row;
    getStockDetailData(row);
};

// 获取库存明细数据
const getStockDetailData = (row) => {
    console.log(curStockDetailData.value,'awkdjnajwd');
    
    let obj = {
        page: stockDetailPageVO.currentPage,
        pageSize: stockDetailPageVO.pageSize,
        inventoryId: curStockDetailData.value.id
    }
    stockManageApi().transactionsInventor(obj).then(res => {
        stockDetailData.value = res.data.list
        stockDetailPageVO.total = res.data.total
        stockDetailDialogVisible.value = true;
    })
    // 这里调用获取库存明细的API，传入分页参数
    // setTimeout(() => {
    //     stockDetailData.value = [
    //         {
    //             type: '入库',
    //             quantity: 100,
    //             remark: '初始入库',
    //             createTime: '2024-01-01 12:00:00'
    //         },
    //         {
    //             type: '出库',
    //             quantity: 20,
    //             remark: '销售出库',
    //             createTime: '2024-01-02 14:30:00'
    //         }
    //     ];
    //     stockDetailPageVO.total = 100; // 设置总数据量
    // }, 500);
};

// 库存明细分页变化
const stockDetailPageChange = ({ pageSize, currentPage }) => {
    stockDetailPageVO.currentPage = currentPage;
    stockDetailPageVO.pageSize = pageSize;
    getStockDetailData();
};
const stockEditRules = {
    productCode: [{ required: true, message: '请输入商品编码', trigger: 'blur' }],
    productName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }]
};

// 编辑库存信息
const handleStockEdit = (row) => {
    Object.assign(stockEditForm, row);
    stockEditDialogVisible.value = true;
};

// 提交编辑
const handleStockEditSubmit = () => {
    stockEditFormRef.value?.validate((valid) => {
        if (valid) {
            stockManageApi().updateInventory(stockEditForm).then(res => {
                console.log(res)
                ElMessage.success('编辑成功');
                stockEditDialogVisible.value = false;
                getStockList();
            })
        }
    });
};

// 添加商品相关
const addProductDialogVisible = ref(false);
const stockEditFormRef = ref();
const addProductFormRef = ref();
const addProductForm = reactive({
    productCode: '',
    productName: '',
    specification: '',
    unit: '',
    quantity: 0,
    remark: ''
});

const addProductRules = {
    productCode: [{ required: true, message: '请输入商品编码', trigger: 'blur' }],
    productName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
    // specification: [{ required: true, message: '请输入规格', trigger: 'blur' }],
    // unit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
    // quantity: [{ required: true, message: '请输入库存数量', trigger: 'blur' }]
};

const handleAddProduct = () => {
    addProductForm.productCode = '';
    addProductForm.productName = '';
    addProductForm.specification = '';
    addProductForm.unit = '';
    addProductForm.quantity = 0;
    addProductForm.remark = '';
    addProductDialogVisible.value = true;
};

const handleAddProductSubmit = () => {
    // addProductForm
    console.log(addProductForm, 'akjwdnk');

    addProductFormRef.value?.validate((valid) => {
        if (valid) {
            stockManageApi().createInventor(addProductForm).then(res => {
                console.log(res)
                ElMessage.success('添加商品成功');
                addProductDialogVisible.value = false;
                getStockList();
            })

        }
    });
};

// 初始化
onMounted(() => {
    getStockList();
    getProductList();
});
</script>

<style scoped lang="scss">
.stock-manage-container {
    .content-wrapper {
        background-color: var(--el-bg-color);
        padding: 20px;
        border-radius: 4px;
    }

    .table-wrapper {
        height: calc(100vh - 200px);
    }
}
</style>